<script setup>
import BlackCard from "@/components/card/BlackCard.vue";
import {onBeforeMount, reactive, ref} from "vue";
import {getVerifyCode, getEmailCode, login, register, checkEmail, forget} from "@/api/api.js";
import {Refresh} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {setSessionStr,isEmpty} from "@/utils/common.ts";
import router from "@/router/router.js";

// 响应式数据 ref 用于基本数据类型及字符串  修改时需要通过.value 获取
// 响应式对象 reactive 用于 obj array等

let isLogin = ref(true);
let codeImg = ref("");
let buttonMsg = ref("获取邮箱验证码");
const countValue = ref(30);
let count = 0;
let isWait = ref(false);
let forgetVisible = ref(false);
let forgetStep = ref(0);
// 响应式对象数据 reactive 用于 obj array等
let userInfo = reactive({
  username: "",
  password: "",
  secPassword: "",
  email: "",
  code: "",
});

const initUserInfo = () => {
  userInfo.username = "";
  userInfo.password = "";
  userInfo.secPassword = "";
  userInfo.email = "";
  userInfo.code = "";
};

const doLogin = () => {
  if (loginValidate(userInfo)) {
    login(userInfo).then(res => {
      if (res) {
        setSessionStr("token", String(res))
        initUserInfo();
        ElMessage.success("登录成功");
        router.push("/center");
      } else {
        ElMessage.error("登录失败");
      }
    }).catch(e => {
      ElMessage.error("服务异常")
    });
  }
};

const loginValidate = (form) => {
  if (isEmpty(form.username)) {
    ElMessage.warning('请输入用户名')
    return false
  }
  if (isEmpty(form.password)) {
    ElMessage.warning('请输入密码')
    return false
  }
  if (isEmpty(form.code)) {
    ElMessage.warning('请输入验证码')
    return false
  }
  return true
}

const doRegister = () => {
  if (registerValidate(userInfo)) {
    register(userInfo).then(res => {
      if (res) {
        ElMessage.success("注册成功,返回登录");
        userInfo.code = "";
        isLogin.value = true;
      } else {
        ElMessage.error("注册失败");
      }
    }).catch(e => {
      ElMessage.error("服务异常")
    });
  }
};

const registerValidate = (form) => {
  if (!loginValidate(form)) {
    return false;
  }
  if (isEmpty(form.secPassword)) {
    ElMessage.warning('请输入确认密码')
    return false
  }
  if (form.secPassword !== form.password) {
    ElMessage.warning('两次密码不一致')
    return false
  }
  if (isEmpty(form.email)) {
    ElMessage.warning('请输入邮箱')
    return false
  }
  return true;
}

const getCode = () => {
  getVerifyCode().then((res) => {
    codeImg.value = res;
  });
}

const getEmail = (operation) => {
  if (!isEmpty(userInfo.email)) {
    getEmailCode(userInfo.email, operation).then(res => {
      if (res) {
        ElMessage.success("验证码发送成功,请到邮箱查看");
        isWait.value = true;
        count = countValue.value;
        let timer = setInterval(() => {
          if (count === 0) {
            clearInterval(timer);
            isWait.value = false;
            buttonMsg.value = "获取邮箱验证码";
          } else {
            buttonMsg.value = count + "s后重试";
            count--;
          }
        }, 1000);
      } else {
        ElMessage.error("发送失败");
      }
    }).catch(e => {
      ElMessage.error("服务异常")
    });
  } else {
    ElMessage.warning("请输入邮箱");
  }
}

const emailSuggestions = (queryString, cb) => {
  let suggestions = [
    {name: "QQ", value: userInfo.email + "@qq.com"},
    {name: "WY", value: userInfo.email + "@163.com"},
    {name: "YH", value: userInfo.email + "@yahoo.com"},
    {name: "GOOGLE", value: userInfo.email + "@gmail.com"},
    {name: "MSN", value: userInfo.email + "@msn.com"},
  ]
  cb(suggestions)
}


const changeLogin = () => {
  isLogin.value = !isLogin.value;
};

const changeForget = () => {
  forgetVisible.value = !forgetVisible.value;
  userInfo.code = "";
  forgetStep.value = 0;
};

const verifyEmail = () => {
  if (isEmpty(userInfo.email)) {
    ElMessage.warning('请先填写账号绑定的邮箱')
    return
  }
  checkEmail(userInfo.email).then(res => {
    if (res) {
      ElMessage.success('已校验邮箱,正在发送验证码,请注意查收')
      getEmailCode(userInfo.email, 4).then(response => {
        if (response) {
          forgetStep.value = 1;
          ElMessage.success("发送成功");
        } else {
          ElMessage.error("发送失败")
        }
      })
    } else {
      ElMessage.error("校验失败");
    }
  });
}

const doReset = () => {
  if (isEmpty(userInfo.password)) {
    ElMessage.warning('请输入新的密码')
    return
  }
  if (isEmpty(userInfo.secPassword)) {
    ElMessage.warning('请输入确认密码')
    return
  }
  if (userInfo.secPassword !== userInfo.password) {
    ElMessage.warning('两次密码不一致')
    return
  }
  if (isEmpty(userInfo.code)) {
    ElMessage.warning('请输入邮箱发送的验证码')
    return
  }
  forget(userInfo).then((res) => {
    if (res) {
      ElMessage.success('提交成功')
      forgetStep.value = 2
    } else {
      ElMessage.error('提交失败')
    }
  })
}

const closeForget = () => {
  ElMessageBox.confirm("确认关闭\nconfirm close?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  }).then(() => {
    changeForget();
  }).catch(() => {
    ElMessage.info("已取消");
  });
}

onBeforeMount(() => {
  getCode();
})
</script>

<template>
  <!-- 铺设独立背景 -->
  <div class="login-container">
    <!-- 通用视窗容器 -->
    <div class="view-container">
      <div class="login-card-container">
        <div id="card-image">
          <div id="card-image-detail">
            <el-image src="/img/blue_logo.png"></el-image>
          </div>
        </div>
        <div id="card-content">
          <div id="card-content-detail">
            <black-card :title="isLogin? '登录':'注册'" :body-style="{padding: '2.5em',height:'100%'}">
              <el-form>
                <el-form-item>
                  <el-input
                      prefix-icon="User"
                      placeholder="输入用户名"
                      v-model="userInfo.username"
                      clearable
                      size="large"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-input
                      prefix-icon="Key"
                      placeholder="输入密码"
                      v-model="userInfo.password"
                      show-password
                      clearable
                      size="large"></el-input>
                </el-form-item>
                <el-form-item v-if="!isLogin">
                  <el-input
                      prefix-icon="Key"
                      placeholder="再次输入密码"
                      v-model="userInfo.secPassword"
                      show-password
                      clearable
                      size="large"></el-input>
                </el-form-item>
                <el-form-item v-if="isLogin">
                  <el-input
                      id="verifyCode"
                      prefix-icon="help"
                      placeholder="输入验证码"
                      v-model="userInfo.code"
                      clearable
                      size="large"
                      @keyup.enter.native="doLogin">
                    <template #append>
                      <el-image
                          id="verifyCode"
                          :src="codeImg"
                          @click="getCode"
                          style="width: 12em; height: 3em">
                        <template #error>
                          <el-icon @click="getCode" style="width:12em;color: #999;">
                            <Refresh/>
                            验证码加载失败
                          </el-icon>
                        </template>
                      </el-image>
                    </template>
                  </el-input>
                  <!-- <v-verifyCode ref="verify" @click.native="getCode"></v-verifyCode> -->
                </el-form-item>
                <el-form-item v-if="!isLogin">
                  <el-autocomplete
                      prefix-icon="Message"
                      placeholder="输入邮箱"
                      v-model="userInfo.email"
                      :fetch-suggestions="emailSuggestions"
                      @select="(item) => {userInfo.email = item.value}"
                      clearable
                      size="large"></el-autocomplete>
                </el-form-item>
                <el-form-item v-if="!isLogin">
                  <el-input
                      prefix-icon="help"
                      placeholder="输入邮箱验证码"
                      v-model="userInfo.code"
                      clearable
                      size="large"
                      @keyup.enter.native="doRegister">
                    <template #append>
                      <el-button v-loading="isWait" @click="getEmail(1)">{{ buttonMsg }}</el-button>
                    </template>
                  </el-input>
                  <!-- <v-verifyCode ref="verify" @click.native="getCode"></v-verifyCode> -->
                </el-form-item>
                <br/>
                <el-form-item v-if="isLogin">
                  <el-button
                      class="loginBtn"
                      color="#FF8D00"
                      size="large"
                      @click="doLogin">登录
                  </el-button>
                </el-form-item>
                <el-form-item v-if="isLogin">
                  <el-button
                      class="loginBtn"
                      color="#535878"
                      size="large"
                      @click="changeLogin">注册
                  </el-button>
                </el-form-item>
                <el-form-item v-if="!isLogin">
                  <el-button
                      class="loginBtn"
                      color="#FF8D00"
                      size="large"
                      @click="doRegister">提交
                  </el-button>
                </el-form-item>
                <el-form-item v-if="!isLogin">
                  <el-button
                      class="loginBtn"
                      color="#535878"
                      size="large"
                      @click="changeLogin">返回登录
                  </el-button>
                </el-form-item>
                <el-form-item v-if="isLogin">
                  <el-button
                      link
                      type="primary"
                      style="width: 100%"
                      @click="changeForget">忘记密码?
                  </el-button>
                </el-form-item>
              </el-form>
            </black-card>
          </div>
        </div>
      </div>
      <el-dialog
          v-model="forgetVisible"
          title="重置密码"
          width="500"
          :before-close="closeForget">
        <!-- 操作步骤 -->
        <el-steps
            :active="forgetStep"
            align-center
            finish-status="success">
          <el-step title="确认账户" icon="Message"></el-step>
          <el-step title="重置密码" icon="Key"></el-step>
          <el-step title="重置成功"></el-step>
        </el-steps>
        <br/>
        <!-- 邮箱校验 -->
        <!-- 限制用户名 -->
        <el-form :model="userInfo" v-if="forgetStep===0">
          <el-form-item prop="email">
            <el-autocomplete
                prefix-icon="Message"
                placeholder="输入邮箱"
                v-model="userInfo.email"
                :fetch-suggestions="emailSuggestions"
                @select="(item) => {userInfo.email = item.value}"
                @keyup.enter.native="verifyEmail"
                clearable
                size="large"></el-autocomplete>
          </el-form-item>
        </el-form>
        <!-- new password -->
        <el-form :model="userInfo" v-if="forgetStep===1">
          <el-form-item>
            <el-input
                prefix-icon="Key"
                placeholder="密码"
                show-password
                v-model="userInfo.password"
                @keyup.enter.native="doReset"
            ></el-input>
            <el-input
                prefix-icon="Key"
                placeholder="密码"
                show-password
                v-model="userInfo.secPassword"
                @keyup.enter.native="doReset"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                prefix-icon="help"
                placeholder="验证码"
                v-model="userInfo.code"
                @keyup.enter.native="doReset"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button
                class="loginBtn"
                color="#FF8D00"
                @click="verifyEmail"
                v-if="forgetStep===0"
            >校验邮箱</el-button>
            <el-button
                class="loginBtn"
                color="#FF8D00"
                @click="doReset"
                v-if="forgetStep===1"
            >提交</el-button>
            <el-button
                class="loginBtn"
                color="#FF8D00"
                @click="changeForget"
                v-if="forgetStep===2"
            >完成</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  background: url("@/assets/login_background_small.png");
  background-size: cover;
}

.login-card-container {
  margin-top: 4em;
  align-items: center;
}

#card-image {
  position: relative;
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: center;
  z-index: 10;
}

#card-image-detail {
  width: 20em;
}

#card-content {
  position: relative;
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: center;
  margin-top: -3em;
}

#card-content-detail {
  width: 35em;
  height: 35em;
  filter: alpha(Opacity=90);
  -moz-opacity: 0.9;
  opacity: 0.9;
}

.loginBtn {
  width: 100%;
  color: #FFFFFF;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .login-container {
    padding: 10px;
  }
  
  .login-card-container {
    margin-top: 2em;
    width: 100%;
  }
  
  #card-image-detail {
    width: 15em;
  }
  
  #card-content-detail {
    width: 90%;
    height: auto;
    margin: 0 auto;
  }

  #verifyCode {
    width: 10em;
    height: 3em;
  }
  
  .el-input {
    font-size: 16px; /* 防止iOS自动缩放 */
  }
  
  .el-input__inner {
    font-size: 16px;
  }
  
  .el-button {
    font-size: 16px;
  }
  
  .el-dialog {
    width: 90% !important;
    margin: 0 auto;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 5px;
  }
  
  .login-card-container {
    margin-top: 1em;
  }
  
  #card-image-detail {
    width: 12em;
  }
  
  #card-content-detail {
    width: 95%;
    height: auto;
  }

  #verifyCode {
    width: 8em;
    height: 3em;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
  
  .el-input {
    font-size: 16px;
  }
  
  .el-input__inner {
    font-size: 16px;
    padding: 12px 15px;
  }
  
  .el-button {
    font-size: 16px;
    padding: 12px 20px;
  }
  
  .el-dialog {
    width: 95% !important;
  }
  
  .el-dialog__body {
    padding: 15px;
  }
}
</style>